package com.sh.controller;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.sh.common.ResponseInfoEnum;
import com.sh.common.ReturnVO;
import com.sh.entity.Role;
import com.sh.entity.User;
import com.sh.service.AccountService;
import com.sh.util.JwtUtil;

import cn.hutool.crypto.SecureUtil;

/**
 *  用户权限相关 controller
 * */
@RestController
@RequestMapping("/api/user")
public class AccountController extends BaseController{
	@Autowired
	AccountService accountService;

	//JWT私钥
	@Value("${jwt.private.key}")
	private String JWT_PRIVATE_KEY = "default";

	//过期时间
	@Value("${accessTokenExpireTime}")
	private String ACCESS_TOKEN_EXPIRE_TIME = "0";



	@ResponseBody
	@RequestMapping("/login")
	public ReturnVO login(
			@RequestParam(value = "username",required = true) String username,
			@RequestParam(value = "password",required = true) String password
	){

		//根据 用户名查询用户
		User user = accountService.getUserByUserName(username);
		//如果用户为空就返回错误信息
		if(user==null)
			return failForService("400",ResponseInfoEnum.USER_NOT_EXIST);


		//比对 密码
		String pwdMd5 = SecureUtil.md5(password);
		String dbPwd = SecureUtil.md5(user.getPwd());
		if(!pwdMd5.equals(dbPwd))
			//如果密码不通过就返回错误信息
			return failForService("400",ResponseInfoEnum.USER_PWD_ERROR);

		//拿取 token
		String token =
				JwtUtil.sign(username, JWT_PRIVATE_KEY,Long.parseLong(ACCESS_TOKEN_EXPIRE_TIME));
		//返回前台的信息
		User rtnUser = new User();
		rtnUser.setUserName(user.getUserName());

		//默认给customer权限
		Role role = new Role();
		role.setRoleName("客户权限");
		role.setRoleId("customer");
		ArrayList<Role> roleList = new ArrayList<Role>();
		roleList.add(role);
		rtnUser.setRole(roleList);
		rtnUser.setToken(token);

		return succForService(ResponseInfoEnum.USER_LOGIN_SUCCESS, rtnUser);

	}


}
